//
//  AXFOrderViewController.m
//  AXFEightGroup
//
//  Created by ooops on 12/22/16.
//  Copyright © 2016 ya. All rights reserved.
//

#import "AXFOrderViewController.h"
#import <objc/message.h>
#import "AXFProductTableViewCell.h"
#import "AXFShoppingButtonView.h"
#import "AXFDetailViewController.h"

#pragma mark - 分类
@interface AXFOrderViewController (UITableViewDataSourceMethods) <UITableViewDataSource> @end
@interface AXFOrderViewController (UITableViewDelegateMethods) <UITableViewDelegate>
#pragma mark - 分类属性
@property (nonatomic, assign, getter=isScroll) BOOL scroll;
#pragma mark -
@end
#pragma mark -





#pragma mark - 延展
@interface AXFOrderViewController () <UIGestureRecognizerDelegate, CAAnimationDelegate>



#pragma mark - 属性
@property (weak, nonatomic) IBOutlet UITableView        *categroyTableView;
@property (nonatomic, strong) NSArray<AXFDataModel *>   *categroyModels;

@property (weak, nonatomic) IBOutlet UITableView        *productTableView;
@property (nonatomic, strong) NSDictionary<NSString *, NSArray<AXFDataModel *> *> *productModels;
#pragma mark -

#pragma mark - 方法
- (NSArray<AXFDataModel *> *)modelsWithSection:(NSInteger)section;
#pragma mark -


@end


#pragma mark -


@implementation AXFOrderViewController

#pragma mark - 配置

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.productTableView reloadData];
}









- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;















    self.productTableView.estimatedRowHeight = 91.0;

    [_ModelMgr products:^(NSDictionary<NSString *, NSArray<AXFDataModel *> *> * _Nullable models) {
        self.productModels = models;
        [self.productTableView reloadData];
    }];
























    NSIndexPath *cofingIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [_ModelMgr categories:^(NSArray<AXFDataModel *> * _Nullable models) {
        self.categroyModels = models;
        [self.categroyTableView reloadData];
        self.categroyTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
        [self.categroyTableView selectRowAtIndexPath:cofingIndexPath
                                            animated:NO
                                      scrollPosition:UITableViewScrollPositionNone];
    }];

    [self addPanGR];


    [self setupNotifications];



    [self tttt];

    // Initialization code
}

- (void)tttt {


    UIImageView *refreshView = nibView(@"AXFOrderRefreshView");
    [self.productTableView addSubview:refreshView];

    CGFloat h = 60.0;

    [refreshView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.trailing.leading.equalTo(self.productTableView);
        make.height.equalTo(@(h));
    }];
}



- (void)addPanGR {
    UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                            action:@selector(handlePanGR:)];
    panGR.delegate = self;
    [self.productTableView addGestureRecognizer:panGR];
}

- (void)handlePanGR:(UIPanGestureRecognizer *)pan {
    [self setScroll:YES];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

- (NSArray<AXFDataModel *> *)modelsWithSection:(NSInteger)section {
    NSString *keyName = self.categroyModels[section].iD;
    NSArray<AXFDataModel *> *models = self.productModels[keyName];
    return models;
}

#pragma mark -


#pragma mark - 配置Notifications

- (void)setupNotifications {

    NotificationCenterAddObserver(self,
                                  Action_AXFShoppingButtonView_Plus,
                                  @selector(action_AXFShoppingButtonView_Plus:));
    NotificationCenterAddObserver(self,
                                  Action_AXFShoppingButtonView_Miuns,
                                  @selector(action_AXFShoppingButtonView_Miuns:));

}


- (void)dealloc {
    NotificationRemoveObserver(self);
}


- (void)action_AXFShoppingButtonView_Plus:(NSNotification *)notification {
    [self setScroll:NO];
    [self.productTableView reloadData];
    if ( ![notification.object isKindOfClass:[AXFProductTableViewCell class]] ) {
        return;
    }
    AXFProductTableViewCell *cell = notification.object;
    [self plusAnimationWithCell:cell];

}


- (void)action_AXFShoppingButtonView_Miuns:(NSNotification *)notification {
    [self setScroll:NO];
    [self.productTableView reloadData];
}



- (void)plusAnimationWithCell:(AXFProductTableViewCell *)cell {
    CGRect rect1 = [cell convertRect:cell.imgImageView.frame toView:self.productTableView];
    CGRect rect = [self.productTableView convertRect:rect1 toView:self.view];

    UIImageView *animationImageView = [[UIImageView alloc] init];
    [animationImageView setFrame:rect];
    [animationImageView setImage:cell.imgImageView.image];
    animationImageView.backgroundColor = [UIColor sj_randomColor];
    [self.view addSubview:animationImageView];








    CAKeyframeAnimation *keyFrameAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, rect.origin.x + 50, rect.origin.y + 50); // 起点
    CGPathAddQuadCurveToPoint(path, NULL, rect.origin.x + 150, rect.origin.y, rect.origin.x + 150, self.view.h);
    keyFrameAnimation.path = path;
    keyFrameAnimation.fillMode = kCAFillModeForwards;
    keyFrameAnimation.removedOnCompletion = NO;
    keyFrameAnimation.delegate = self;
    [keyFrameAnimation setValue:animationImageView forKey:@"imageView"];
    CGPathRelease(path);
    keyFrameAnimation.duration = 0.5;
    [animationImageView.layer addAnimation:keyFrameAnimation forKey:@"anima"];












    CABasicAnimation *scaleAnima = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    scaleAnima.fromValue = [NSNumber numberWithFloat:1.5];
    scaleAnima.toValue = [NSNumber numberWithFloat:0.35];
    scaleAnima.fillMode = kCAFillModeForwards;
    scaleAnima.removedOnCompletion = NO;
    scaleAnima.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    scaleAnima.duration = 0.5;
    [animationImageView.layer addAnimation:scaleAnima forKey:@"scaleAnimation"];
}


// MARK: CAAnimationDelegate

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    UIImageView *imageView = [anim valueForKey:@"imageView"];
    [imageView removeFromSuperview];
}





#pragma mark -


@end

@implementation AXFOrderViewController (UITableViewDataSourceMethods)

#pragma mark - UITableViewDataSourceMethods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == self.productTableView) {
        return self.productModels.count;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == self.productTableView) {
        return [self modelsWithSection:section].count;
    }
    return self.categroyModels.count;
}

- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (tableView == self.productTableView) {
        return self.categroyModels[section].name;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *categroyCellID = @"AXFCategroyTableViewCellID";
    static NSString *productCellID  = @"AXFProductTableViewCellID";

    NSString *cellID = (tableView == self.categroyTableView) ? categroyCellID : productCellID;

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

    if (tableView == self.categroyTableView) {
        cell = nibView(@"AXFCategroyTableViewCell");
        cell.textLabel.text = self.categroyModels[indexPath.row].name;
    }
    else if (tableView == self.productTableView) {
        cell = nibView(@"AXFProductTableViewCell");
        [cell setValue:[self modelsWithSection:indexPath.section][indexPath.row]
                forKey:@"model"];
    }
    return cell;
}





#pragma mark -

@end

@implementation AXFOrderViewController (UITableViewDelegateMethods)

#pragma mark - UITableViewDelegate

#define kCategroyTableViewScrollSwitch "kCategroyTableViewScrollSwitch"

- (void)setScroll:(BOOL)scroll {
    objc_setAssociatedObject(self, kCategroyTableViewScrollSwitch, @(scroll), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)isScroll {
    return [objc_getAssociatedObject(self, kCategroyTableViewScrollSwitch) boolValue];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if (tableView == self.categroyTableView) {
        NSInteger newRow      = 0;
        NSInteger newSection  = indexPath.row;
        NSIndexPath *scroll   = [NSIndexPath indexPathForRow:newRow
                                                   inSection:newSection];

        [self.productTableView scrollToRowAtIndexPath:scroll
                                     atScrollPosition:UITableViewScrollPositionTop
                                             animated:YES];
        [self setScroll:NO];
        return;
    }










    
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell) {
        [UIView animateWithDuration:0.25 animations:^{
            cell.transform = CGAffineTransformMakeScale(0.8, 0.8);
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.1 animations:^{
                cell.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                AXFDetailViewController *detail = [AXFDetailViewController new];
                detail.model = [self modelsWithSection:indexPath.section][indexPath.row];
                [self.navigationController pushViewController:detail animated:YES];
            }];
        }];
    }
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (self.isScroll == NO) {
        return;
    }

    if (tableView == self.productTableView) {
        NSInteger               mdoelsCount = [self modelsWithSection:indexPath.section].count;
        NSArray<NSIndexPath *> *visibleRows = [self.productTableView indexPathsForVisibleRows];
        NSIndexPath            *first       = visibleRows.firstObject;

        /// 如果数组的第一个IndexPath是(section, count - 1), 说明分类View需要切换'first'(0 Section).
        if (first.row == (mdoelsCount - 1)) {
            NSInteger newRow      = first.section;
            NSInteger newSection  = 0;
            NSIndexPath *scroll   = [NSIndexPath indexPathForRow:newRow
                                                       inSection:newSection];

            [self.categroyTableView selectRowAtIndexPath:scroll
                                                animated:YES
                                          scrollPosition:UITableViewScrollPositionTop];
        }











        NSIndexPath *firstIndexPath = visibleRows[0];
        cell.layer.anchorPoint = CGPointMake(0, 0.5);
        CGFloat cellPositonX   = cell.layer.position.x;
        cell.layer.position = CGPointMake(0, cell.layer.position.y);
        if (firstIndexPath.row < indexPath.row) {
            cell.layer.transform = CATransform3DMakeRotation(M_PI_2, 0, 0, 1.0);
        }else{
            cell.layer.transform = CATransform3DMakeRotation(- M_PI_2, 0, 0, 1.0);
        }
        cell.alpha = 0.0;
        [UIView animateWithDuration:0.25 animations:^{
            cell.layer.transform = CATransform3DIdentity;
            cell.alpha = 1.0;
        } completion:^(BOOL finished) {
            cell.layer.anchorPoint = CGPointMake(0.5, 0.5);
            cell.layer.position = CGPointMake(cellPositonX, cell.layer.position.y);
        }];
    }
    
    
    
    
    
}

- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath*)indexPath {

    if (self.isScroll == NO) {
        return;
    }

    if (tableView == self.productTableView) {
        NSArray<NSIndexPath *> *visibleRows = [self.productTableView indexPathsForVisibleRows];
        NSIndexPath            *first       = visibleRows.firstObject;

        /// 如果数组的第一个IndexPath是(section, 0), 说明分类View需要切换'first'(0 Section).
        if (first.row == 0) {
            NSInteger newRow      = first.section;
            NSInteger newSection  = 0;
            NSIndexPath *scroll   = [NSIndexPath indexPathForRow:newRow
                                                       inSection:newSection];

            [self.categroyTableView selectRowAtIndexPath:scroll
                                                animated:YES
                                          scrollPosition:UITableViewScrollPositionNone];
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return tableView == self.categroyTableView ? 0.1 : 30.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

#pragma mark -

@end
